package com.dlyk.service.impl;

import com.dlyk.bean.TActivity;
import com.dlyk.constant.Constants;
import com.dlyk.mapper.TActivityMapper;
import com.dlyk.query.ActivityQuery;
import com.dlyk.query.BaseQuery;
import com.dlyk.service.ActivityService;
import com.dlyk.utils.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private TActivityMapper tActivityMapper;

    /**
     * 活动分页查询
     * @param current
     * @return
     */
    @Override
    public PageInfo<TActivity> getActivityByPage(Integer current,ActivityQuery activityQuery) {
        // 设置分页
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        // 开始查询
        List<TActivity> activityList= tActivityMapper.selectByActivityPage(activityQuery);
        // 封装分页数据
        PageInfo<TActivity> info = new PageInfo<>(activityList);
        return info;
    }

    /**
     * 录入市场活动
     * @param activityQuery
     * @return
     */
    @Override
    public int saveActivity(ActivityQuery activityQuery) {
        TActivity tActivity = new TActivity();
        BeanUtils.copyProperties(activityQuery,tActivity);
        // 设置创建时间
        tActivity.setCreateTime(new Date());
        // 获取登录人id
        Integer userId = JWTUtils.parseUserFromJWT(activityQuery.getToken()).getId();
        tActivity.setCreateBy(userId);

        return tActivityMapper.insertSelective(tActivity);
    }

    /**
     * 根据id查询市场活动信息
     * @param id
     * @return
     */
    @Override
    public TActivity selectById(Integer id) {
        TActivity activity = tActivityMapper.selectDetailByPrimaryKey(id);
        return activity;
    }

    /**
     * 编辑市场活动
     * @param activityQuery
     * @return
     */
    @Override
    public int updateActivity(ActivityQuery activityQuery) {
        TActivity activity = new TActivity();
        BeanUtils.copyProperties(activityQuery,activity);

        // 设置编辑时间
        activity.setEditTime(new Date());
        Integer id = JWTUtils.parseUserFromJWT(activityQuery.getToken()).getId();

        // 设置编辑人
        activity.setId(id);
        activity.setEndTime(new Date());
        activity.setEditBy(id);

        // 修改市场活动信息
        return tActivityMapper.updateByPrimaryKeySelective(activity);
    }

    /**
     * 查询正在进行的市场活动
     * @return
     */
    @Override
    public List<TActivity> getOnActivity() {
        return tActivityMapper.getOnActivity();
    }
}
